package com.zhz.mall.common.constraints;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Sets;
import com.zhz.mall.common.annotation.StringContains;
import com.zhz.mall.common.util.enums.EnumValueResolver;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhouhengzhe
 */
public class StringContainsValidator implements ConstraintValidator<StringContains, String> {

    private Set<String> scopes = new HashSet<>();

    private Pattern pattern;

    @Override
    public void initialize(StringContains constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        String[] scope = constraintAnnotation.scope();
        if (scope != null && scope.length > 1) {
            scopes = Sets.newHashSet(scope);
        }
        Class<? extends EnumValueResolver> aClass = constraintAnnotation.scopeEnum();
        if (!aClass.isInterface()) {
            EnumValueResolver[] enumConstants = aClass.getEnumConstants();
            for (EnumValueResolver enumConstant : enumConstants) {
                scopes.add(enumConstant.getDesc());
            }
        }
        pattern = Pattern.compile(constraintAnnotation.scopeRegex());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return true;
        }
        if (scopes.contains(value)) {
            return true;
        }
        Matcher m = pattern.matcher(value);
        return m.matches();
    }
}
